package utils;

import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Set;

public class CleanSessionsThread extends Thread {

    private static final String recent = "recent:";
    private static final String viewed = "viewed:";
    private static final String login = "login:";

    private Jedis conn;
    private int limit;
    private boolean quit;

    public CleanSessionsThread(int limit) {
        this.conn = new Jedis("192.168.179.21", 6379);
        this.conn.select(15);
        this.limit = limit;
    }

    public void  quit(){
        quit = true;
    }

    @Override
    public void run() {
        while (!quit) {
            //找出目前已有令牌的数量
            Long size = conn.zcard(recent);
            //令牌数量未超过限制，休眠并在之后重新检查
            if (size <= limit) {
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                continue;
            }
            //获取需要移除的令牌ID
            long endIndex = Math.min(size - limit, 100);
            Set<String> tokenSet = conn.zrange(recent, 0, endIndex - 1);
            String[] tokens = tokenSet.toArray(new String[tokenSet.size()]);

            //为那些将要移除要被删除的令牌构建健名
            ArrayList<String> sessionKey = new ArrayList<>();
            for (String token :tokens){
               sessionKey.add(viewed+token);
            }
            //移除最旧的那些令牌
            conn.del(sessionKey.toArray(new String[sessionKey.size()]));
            conn.hdel(login,tokens);
            conn.zrem(recent,tokens);
        }
    }


}
